<template>
  <div class="oc-collapse">
    <slot></slot>
  </div>
  {{ activeNames }}
</template>

<script setup lang="ts">
import type { NameType, CollapseProps, CollapseEmits } from './types'
import { ref, provide, watch } from 'vue'
import { CollapseContextKey } from './types'
defineOptions({
  name: 'OcCollapse',
})
const props = defineProps<CollapseProps>()
const emits = defineEmits<CollapseEmits>()
watch(
  () => props.modelValue,
  () => {
    activeNames.value = props.modelValue
  },
)
const activeNames = ref<NameType[]>(props.modelValue)
if (props.accorditon && activeNames.value.length > 1) {
  console.warn('手风琴模式下应该初始只有一个被激活')
}
const handleItemClick = (item: NameType) => {
  if (props.accorditon) {
    activeNames.value = [activeNames.value[0] === item ? '' : item]
  } else {
    const index = activeNames.value.indexOf(item)
    if (index > -1) {
      // 存在，表示关闭。删除数组对应项
      activeNames.value.splice(index, 1)
    } else {
      // 不存在，插入对应的name
      activeNames.value.push(item)
    }
  }

  emits('update:modelValue', activeNames.value)
}
provide(CollapseContextKey, {
  activeNames,
  handleItemClick,
})
</script>

<style scoped></style>
